//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;

using NHibernate.Criterion;

using ProjectBase.Core;
using ProjectBase.Data;

using Survey.Common;
using Survey.Common.Data;
using Survey.Entity;

namespace Survey.Data
{
    public class ContentTypeDao : CodeListBaseDao<ContentType, ContentTypeFilter>, IContentTypeDao
    {
        #region IContentTypeDao Members
        /// <summary>
        ///     Evaluates all filters and order-by clauses
        ///     and returns sorted list of matching CodeList entities
        /// </summary>
        /// <param name = "filter">ISearchObject&lt;CodeList&gt; containing CodeListFilter not-null instance</param>
        /// <returns>List of CodeList entities matching the searching criteria</returns>
        public override IEnumerable<ContentType> Find(ContentTypeFilter filter)
        {
            Criteria.AddLike(() => filter.Suffix);
            return base.Find(filter);
        }

        /// <summary>
        ///     Sets the ID to the last + 1
        /// </summary>
        /// <param name = "entity"></param>
        /// <returns></returns>
        public override ContentType Add(ContentType entity)
        {
            var last = GetEntityWithMaxId();
            entity.SetId((last.Is()
                              ? last.ID + 1
                              : 1));
            entity = base.Add(entity);
            Session.Flush();
            return entity;
        }
        #endregion

        /// <summary>
        ///     Gets the Last used ID
        /// </summary>
        /// <returns></returns>
        public virtual ContentType GetEntityWithMaxId()
        {
            return Session
                .CreateCriteria<ContentType>()
                .AddOrder(new Order(Str.Common.ID, false))
                .SetMaxResults(1)
                .UniqueResult<ContentType>();
        }
    }
}